package edu.chalmers;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockFragmentActivity {
	private SharedBookManager bookManager = SharedBookManager.getBookManager();
	private ActionBar actionBar;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        
        int position;
        if(savedInstanceState != null){
            position = savedInstanceState.getInt("selected_tab");
        } else{
            position = 0;
        }
        
        loadBooks();
        
        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);
        
        ActionBar.Tab collectionTab = actionBar.newTab();
        collectionTab.setText("Collection");
        collectionTab.setIcon(R.drawable.collections_view_as_list);
        collectionTab.setTabListener(
        		new TabListener<CollectionFragment>(
        				this, getString(R.string.collection), CollectionFragment.class));
        
        ActionBar.Tab summaryTab = actionBar.newTab();
        summaryTab.setText("Summary");
        summaryTab.setIcon(R.drawable.action_about);
        summaryTab.setTabListener(
        		new TabListener<SummaryFragment>(
        				this, getString(R.string.summary), SummaryFragment.class));
        
        actionBar.addTab(collectionTab);
        actionBar.addTab(summaryTab);
        actionBar.setSelectedNavigationItem(position);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.collection_menu, menu);
        return true;
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("selected_tab", actionBar.getSelectedNavigationIndex());
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	int id = item.getItemId();
//    	switch (item.getItemId()) {
//    		case R.id.menu_addBook:
    	if(id == R.id.menu_addBook){
    			Intent intent = new Intent(this, AddActivity.class);
    			startActivity(intent);
    			return true;
    	} else{
//    		default:
    			return super.onOptionsItemSelected(item);
    	}
    };
    
    private void loadBooks(){
    	SharedPreferences settings = getSharedPreferences("prefs", 0);
        HashSet<String> header = (HashSet<String>) settings.getStringSet("header", null);
        ArrayList<Book> loadedBooks = new ArrayList<Book>();
        if(header != null){
        	for(String bookTitle : header){
        		HashSet<String> bData = (HashSet<String>)settings.getStringSet(bookTitle, null);
        		Iterator<String> dataIterator = bData.iterator();
        		String author = dataIterator.next();
        		String title = dataIterator.next();
        		String course = dataIterator.next();
        		String price = dataIterator.next();
        		String isbn = dataIterator.next();
        		loadedBooks.add(new Book(author, title, isbn, course, Integer.parseInt(price)));
        	}
        	bookManager.loadBooks(loadedBooks);
        }
    }
    
    private class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private Fragment fragment;
        private SherlockFragmentActivity activity;
        private String tag;
        private Class<T> mClass;
        
        public TabListener(SherlockFragmentActivity activity, String tag, Class<T> cls){
        	this.activity = activity;
        	this.tag = tag;
        	mClass = cls;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
        	fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
        	if (fragment == null) {
        		fragment = Fragment.instantiate(activity, mClass.getName());
                ft.add(android.R.id.content, fragment, tag);
            } else {
                ft.attach(fragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        	if (fragment != null) {
        		ft.detach(fragment);
        	}
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }
    }
}